package web.filemanager.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
public class LoginController {

    @PostMapping("/LoginServlet")
    @ResponseBody
    public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
        // 数据库连接信息
        String url = "jdbc:mysql://localhost:3306/file_management";
        String dbUsername = "root";
        String dbPassword = "shujuku";

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            // 加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 连接数据库
            conn = DriverManager.getConnection(url, dbUsername, dbPassword);

            // 准备查询语句
            String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            stmt.setString(2, password);

            // 执行查询
            rs = stmt.executeQuery();          // 检查是否存在匹配的用户
            if (rs.next()) {
                // 用户验证成功
                return "success";
            } else {
                // 用户验证失败
                return "failure";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        } finally {
            // 关闭数据库连接
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
